﻿(function(){
//根据省份获得城市
    var pop = (function(){
        var userBankData,$input,$probox,$provincebox,$citybox,$cityboxcon,$cityid;
        //加载数据
        function getUserBankData(){
            $.ajax({
                url:"/common/bank/bankData.js",
                async:false,
                dataType:"JSON",
                success:function(data){
                    userBankData=data;
                }
            });
        }

        //对数据进行转换，排序
        function tansData(){
            var regions = ['华北', '东北', '华东', '中南', '西南', '西北' ];
            var provinces = [];
            if(typeof(userBankData) == "undefined"){
                getUserBankData();
            }
            var myobj = userBankData;
            $.each(myobj.datas,function(k,v){
                provinces.push(v.province+"|"+ v.region);
            });

            provinces=unique(provinces,function(v1,v2){
                return v1.split("|")[0] === v2.split("|")[0];
            });
            provinces = swapCity(provinces);
            $provincebox.empty().hide();

            $.each(regions,function(k,v){
                var $areadiv= $("<div class='areadiv' data="+v+"></div>");
                $areadiv.html(v);
                $provincebox.append($areadiv);
            });
            $.each(provinces,function(k,v){
                var arr= v.split("|");
                var $span=$("<span data-province="+arr[0]+">"+ arr[0]+"</span>");
                $(".areadiv[data='"+arr[1]+"']").append($span);
            });
            $provincebox.undelegate("click").delegate("span","click",function(){
                var province=$(this).attr("data-province");
                showCity($(this),province);
            }).show();

            $probox.show();
        }

        //根据省份显示城市
        function showCity(obj,province){
            var myobj = userBankData;
            var city = [];
            var left = obj[0].offsetLeft;
            var top = obj[0].offsetTop;
            $cityboxcon.empty();
            $.each(myobj.datas,function(k,v){
                if(v.province == province){
                    city.push({city:v.city,value:v.id});
                }
            });

            $.each(city,function(k,v){
                var $cityspan = $("<a class='citydiv' data-city='"+v.city+"' data-value='"+v.value+"'>"+v.city+"</a>");
                $cityboxcon.append($cityspan);
            });

            $citybox.css({
                "left" : function() {
                    var wid = $(this).width();
                    if (wid + left >= $probox.width()) {
                        return left - wid + 20 + "px";
                    }
                    return left + "px";
                },
                "top" : function() {
                    var hei = $(this).height();
                    if (hei + top >= $probox.height()) {
                        return top - hei - 20 + "px";
                    }
                    return top + 20 + "px";
                }
            }).show();
            $cityboxcon.undelegate("click").delegate("a","click",function(){
                var city = $(this).attr("data-city");
                $input.val(province+" "+city).trigger("blur");
                $cityid.val($(this).attr("data-value"));
                $probox.hide();
            });
        }

        //对市放在最前(北京市放在最前)，把区放在最后
        function swapCity(arr){
            var tmparr1=[],tmparr2=[],tmparr3=[],tmparr4=[],backarr=[],i = 0,len = arr.length;
            for(;i<len;i++){
                if(/北京市/.test(arr[i])){
                    tmparr1.push(arr[i]);
                }else if(/市/.test(arr[i])){
                    tmparr2.push(arr[i]);
                }else if(/区/.test(arr[i])){
                    tmparr4.push(arr[i]);
                }else{
                    tmparr3.push(arr[i]);
                }
            }
            backarr= $.merge(tmparr1,tmparr2);
            backarr= $.merge(backarr,tmparr3);
            backarr= $.merge(backarr,tmparr4);
            return backarr;
        }

        //对数组中相同的元素进行去重
        function unique(source, compareFn) {
            var len = source.length, result = source.slice(0), i, datum;
            if ('function' != typeof compareFn) {
                compareFn = function(item1, item2) {
                    return item1 === item2;
                };
            }
            // 从后往前双重循环比较
            // 如果两个元素相同，删除后一个
            while (--len > 0) {
                datum = result[len];
                i = len;
                while (i--) {
                    if (compareFn(datum, result[i])) {
                        result.splice(len, 1);
                        break;
                    }
                }
            }
            return result;
        }

        //初始化
        function init(){
            $cityid = $("#cityid");
            $input  = $("#bank_area");
            $probox = $("<div class='probox'></div>").css({top:$input[0].offsetHeight}).insertAfter($input);
            $provincebox = $("<div id='provincebox'></div>");
            $citybox = $("<div id='citybox'></div>");
            var cityboxClose = $("<span class='close'>X</span>").click(function(){
                $citybox.hide();
            }).appendTo($citybox);
            $cityboxcon = $("<div id='cityboxcon'></div>");
            $citybox.append($cityboxcon);
            var $proboxClose = $("<span class='close'>X</span>").click(function(){
                $probox.hide();
                $citybox.hide();
            }).appendTo($probox);
            $probox.append($provincebox).append($citybox).parent().css("position","relative");
            $input.bind("focus",function(){
                tansData();
            }).bind("keyup",function(){
                    this.value="";
                });
        }

        return {
            init:function(){
                init();
            }
        };

    })();

//对银行开户行进行搜索
    var search = (function(){
        var $bankSearch , $bankKeySearchId ,$cardDeposit ,$selBankType ,$cityid;
        function search(){
            var bankAreaName = $.trim($cardDeposit.val());
            var selBankType = $selBankType.val();
            if (!selBankType || 'other' == selBankType) {
                alert("请选择银行");
                return;
            }
            $.ajax({
                url : "/bankdb/bankdb!listBankDetails.action",
                type : "POST",
                data : {
                    "city" : $cityid.val(),
                    "bank" : selBankType,
                    "key" : bankAreaName
                },
                dataType : "JSON",
                error : function() {
                    alert("银行数据加载失败，请刷新后重试");
                },
                beforeSend : function() {
                    $bankSearch.html("<img src='/static/img/loading.gif' />").show();
                },
                success : function(data) {
                    var d = data, tmpLi = "";
                    if (d.datas && d.datas.length) {
                        $.each(d.datas,function(i, n) {
                            tmpLi += "<li>"+ n.name + "</li>";
                        });
                    } else {
                        tmpLi += "<p>没有匹配支行信息</p>";
                    }
                    $bankSearch.html(tmpLi);
                    $(document.body).click(function(e) {
                        if (e.target.id !== "bankKeySearchId"&& e.target.id != "bankSearch") {
                            $bankSearch.hide();
                        }
                    });
                    $bankSearch.delegate("li","click",function(){
                        var html=$(this).html();
                        $cardDeposit.val(html).trigger("blur");
                    }).delegate("li","mouseover",function(){
                            $(this).addClass("enter");
                        }).delegate("li","mouseout",function(){
                            $(this).removeClass("enter");
                        });
                }

            });

        }
        function init(){
            $selBankType = $("#selBankType");
            $bankKeySearchId = $("#bankKeySearchId");
            $cardDeposit = $("#cardDeposit");
            $bankSearch = $("<div class='bankSearch'></div>").css({top:$cardDeposit[0].offsetHeight}).insertAfter($cardDeposit);
            $cityid= $("#cityid");
            $bankKeySearchId.click(function(e){
                search();
                e.stopPropagation();
                return false;
            });
            $selBankType.change(function(){
                $cardDeposit.val("");
            });

        }
        return {
            init:function(){
                init();
            }
        };
    })();

    var addcard = {
        pop:pop,
        search:search
    };

	window.addcard = addcard;
})();

